<template>
  <a-form @submit="handleSubmit" :form="form" class="form-group">
    <create-form title="患者信息" :formSource="baseInfoForm" :formData="defaultData" :status="status" @onGetInfo="getApplyInfo"/>
    <br/>
    <create-form :title="from === 'report'? '转出医院信息(他院)' : '转出医院信息(本院)'" :formSource="outInfoForm" :formData="defaultData" :status="status"/>
    <br/>
    <create-form :title="from === 'report'? '转入医院信息(本院)' : '转入医院信息(他院)'" :formSource="rollinInfoForm" :formData="defaultData" :status="status"/>
    <a-form-item v-if="showSubmit">
      <a-button htmlType="submit">Submit</a-button>
    </a-form-item>
  </a-form>
</template> 

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import moment from 'moment'
import CreateForm from './CreateForm'
import { refOutApplyInfo , uploadFile } from '@/api/referral'
import { getHospitalInfo, getHospitalInfoOut, getHospDeptInfo, getDoctorInfoList } from '@/utils/dict'
export default {
  name: 'ApplyForm',
  components: {
    CreateForm
  },
  props: {
    from: {
      type: String,
      default: ''
    },
    showSubmit: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: 'add'
    },
    data: {
      type: Object,
      default: null
    },
    disabledList: {
      type: Array,
      default: null
    }
  },
  data () {
    return {
      form: this.$form.createForm(this),
      baseInfoForm: {
        zyh: {
          label: '住院号',
          key: 'zyh',
          rules: { required: true, whitespace: true },
          type: 'inputSearch',
          onSearch: this.getApplyInfo
          // 'disabled': true
        },
        patientName: {
          label: '姓名',
          key: 'patientName',
          rules: { required: true, whitespace: true },
          type: 'input',
          validator: 'validate'
          // 'disabled': true
        },
        patientGender: {
          label: '性别',
          key: 'patientGender',
          rules: { required: true, whitespace: true },
          type: 'radio',
          radioList: {}
        },
        patientAge: {
          label: '年龄',
          key: 'patientAge',
          rules: { required: true, whitespace: true },
          type: 'input',
          inputType: 'text',
          validator: 'validateAge'
        },
        patientCertificateType: {
          label: '证件类型',
          key: 'patientCertificateType',
          rules: { required: true, whitespace: true },
          type: 'select',
          selectList: {}
        },
        patientIdcard: {
          label: '证件号码',
          key: 'patientIdcard',
          placeholder: '',
          rules: { required: true, whitespace: true },
          type: 'input'
        },
        patientMedicareType: {
          label: '医保类型',
          key: 'patientMedicareType',
          rules: { required: true, whitespace: true },
          type: 'select',
          selectList: {}
        },
        patientPhone: {
          label: '手机号码',
          key: 'patientPhone',
          rules: { required: false },
          type: 'input'
        },
        patientType: {
          label: '患者类型',
          key: 'patientType',
          rules: { required: true },
          type: 'radio',
          radioList: {}
        },
        patientMedicareNumber: {
          label: '医保号',
          key: 'patientMedicareNumber',
          rules: { required: true },
          type: 'input'
        },
        patientAddress: {
          label: '家庭住址',
          key: 'patientAddress',
          rules: { required: true },
          type: 'input',
          colspan: 18
        }
      },
      outInfoForm: {
        outHospitalCode: {
          label: '转出医院',
          key: 'outHospitalCode',
          rules: { required: true, whitespace: true },
          type: 'select',
          onChange: this.outHospitalChange,
          showSearch: true,
          selectList: []
        },
        outHospitalName: {
          label: '转出医院名称',
          key: 'outHospitalName',
          hidden: true,
          rules: { required: true },
          type: 'input'
        },
        outDeptCode: {
          label: '转出科室',
          key: 'outDeptCode',
          rules: { required: true, whitespace: true },
          type: 'select',
          onChange: this.outDeptChange,
          showSearch: true,
          selectList: []
        },
        outDeptName: {
          label: '转出科室名称',
          key: 'outDeptName',
          hidden: true,
          rules: { required: true },
          type: 'input'
        },
        outDoctorCode: {
          label: '转出医生',
          key: 'outDoctorCode',
          rules: { required: false },
          type: 'select',
          onSearch: this.outDoctorSearch,
          onChange: this.outDoctorChange,
          showSearch: true,
          selectList: []
        },
        outDoctorName: {
          label: '转出医生名称',
          key: 'outDoctorName',
          hidden: true,
          rules: { required: false },
          type: 'input'
        },
        primaryDiagnosis: {
          label: '初步诊断',
          key: 'primaryDiagnosis',
          placeholder: '请输入初步诊断',
          rules: { required: true, whitespace: true },
          type: 'input',
          colspan: 24
        },
        fileNameList: {
          label: '诊断附件',
          key: 'fileNameList',
          rules: { required: false },
          type: 'fileUpload',
          colspan: 24,
          accept : '.jpg,.png,.doc,.xlsx',
          headers : {authorization: 'authorization-text' , token : Vue.ls.get(ACCESS_TOKEN)},
          uploadList : [],
          handleChange : this.handleChange_fujian,
          beforeUpload: this.beforeUpload_fujian,
          isUpload : true, //是否有上传按钮
          isDelete : true, //是否允许移除已上传的
          tip : '注：任一附件大小不能超过5M，支持照片和文档上传'
        },
        outReason: {
          label: '转诊原因',
          key: 'outReason',
          rules: { required: true },
          type: 'input',
          colspan: 24
        }
      },
      rollinInfoForm: {
        hospitalTurn: {
          label: '转出方向',
          key: 'hospitalTurn',
          rules: { required: true },
          type: 'radio',
          radioList: {},
          colspan: 24
        },
        inHospitalCode: {
          label: '转入医院',
          key: 'inHospitalCode',
          rules: { required: true },
          type: 'select',
          onChange: this.inHospitalChange,
          showSearch: true,
          selectList: []
        },
        inHospitalName: {
          label: '转入医院名称',
          key: 'inHospitalName',
          hidden: true,
          rules: { required: false },
          type: 'input'
        },
        inDeptCode: {
          label: '转入科室',
          key: 'inDeptCode',
          rules: { required: false },
          type: 'select',
          onChange: this.inDeptChange,
          showSearch: true,
          selectList: []
        },
        inDeptName: {
          label: '转入科室名称',
          key: 'inDeptName',
          hidden: true,
          rules: { required: false },
          type: 'input'
        },
        inDoctorCode: {
          label: '转入医生',
          key: 'inDoctorCode',
          rules: { required: false },
          type: 'select',
          onSearch: this.inDoctorSearch,
          onChange: this.inDoctorChange,
          showSearch: true,
          selectList: []
        },
        inDoctorName: {
          label: '转入医生名称',
          key: 'inDoctorName',
          hidden: true,
          rules: { required: false },
          type: 'input'
        },
        inPlanTime: {
          label: '转入时间',
          key: 'inPlanTime',
          rules: { required: false },
          type: 'dateTime',
          showTime: true,
          format: 'YYYY-MM-DD HH:mm:ss',
          colspan: 6
        },
        remark: {
          label: '备注',
          key: 'remark',
          placeholder: '',
          rules: { required: false },
          type: 'input',
          colspan: 24
        }
      },
      pageStatus: this.status, // edit|add|details
      defaultData: {
        zyh: undefined,
        patientName: undefined,
        patientGender: undefined,
        patientAddress: undefined,
        patientAge: undefined,
        patientCertificateType: undefined,
        patientIdcard: undefined,
        patientMedicareNumber: undefined,
        patientMedicareType: undefined,
        patientPhone: undefined,
        patientType: undefined,
        outDeptCode: undefined,
        outDeptName: undefined,
        outDoctorCode: undefined,
        outDoctorName: undefined,
        outHospitalName: undefined,
        outHospitalCode: undefined,
        outReason: undefined,
        // outTime: '',
        primaryDiagnosis: undefined,
        hospitalTurn: undefined,
        inDeptName: undefined,
        inDeptCode: undefined,
        inDoctorName: undefined,
        inDoctorCode: undefined,
        inHospitalName: undefined,
        inHospitalCode: undefined,
        inPlanTime: undefined,
        remark: undefined,
        fileNameList : [], //上传成功的附件
      },
      uploadFileList : [],
      uploadFileBaseUrl : '/dfs/dfs/downloadByFeign/', //上传文件的下载链接
    }
  },
  created () {
    //字典数据-性别
    this.getFormDict('refpatientGender').then(list => {
      this.baseInfoForm.patientGender.radioList = list
    })
    //字典数据-
    this.getFormDict('refpatientCertificateType').then(list => {
      this.baseInfoForm.patientCertificateType.selectList = list
    })
    //字典数据-
    this.getFormDict('refpatientMedicareType').then(list => {
      this.baseInfoForm.patientMedicareType.selectList = list
    })
    //字典数据-
    this.getFormDict('refpatientType').then(list => {
      this.baseInfoForm.patientType.radioList = list
    })
    //字典数据-
    this.getFormDict('refhospitalTurn').then(list => {
      this.rollinInfoForm.hospitalTurn.radioList = list
    })


    // 详情展示元素禁止编辑
    this.onDisabled(this.baseInfoForm)
    this.onDisabled(this.outInfoForm)
    this.onDisabled(this.rollinInfoForm)
    // edit|add|details
    if (this.pageStatus == 'add') {
      //医院字典服务
      getHospitalInfo().then((res) => {
        this.rollinInfoForm.inHospitalCode.selectList = res
      })
      //医院字典转出服务
      getHospitalInfoOut().then((res) => {
        this.outInfoForm.outHospitalCode.selectList = res
      })
    } else {
      //医院字典服务
      getHospitalInfo().then((res) => {
        this.rollinInfoForm.inHospitalCode.selectList = res
        this.outInfoForm.outHospitalCode.selectList = res
      })
      //详情则合并数据源
      this.data && (this.defaultData = Object.assign(this.defaultData, this.data))
      this.outInfoForm.fileNameList.tip = '若有附件，可点击下载进行查阅'
      this.outInfoForm.fileNameList.isUpload = false
      this.outInfoForm.fileNameList.isDelete = false
      
      //附件地址拼接
      if(this.defaultData.fileNameList && this.defaultData.fileNameList.length > 0){
        var arr = []
        this.defaultData.fileNameList.map((fileName)=>{
          arr.push(this.uploadFileBaseUrl + fileName)
        })
        this.outInfoForm.fileNameList.uploadList = arr
      }
      
      
      this.$nextTick(() => {
        this.viewInit()
      })
    }
    
  },
  methods: {
    beforeUpload_fujian(file){
      var passArr = ['application/msword','text/plain','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','image/png','image/jpg','image/jpeg','application/vnd.ms-excel']
      //文件格式
      if(!passArr.find(item=>item == file.type)){
        this.$message.error('文件格式不正确！')
        return false;
      }
      //文件太大
      if(file.size > 1024*1000*5){
        this.$message.error('文件太大！')
        return false;
      }
      return true
    },
    //上传事件-附件
    handleChange_fujian(e){
      var file = e.file;
      console.log('上传附件' , file.status)
      if(file.status != "done"){
        return;
      }
      if(!file.response || file.response.code != 200){
        this.$message.error('上传附件失败！')
        return;
      }
      this.uploadFileList.push( this.uploadFileBaseUrl + file.response.fileName)
      //组件传值
      this.outInfoForm.fileNameList.uploadList = this.uploadFileList
      
    },
    moment,
    getApplyInfo (val, e) {
      var that = this
      if (val) {
        refOutApplyInfo({ zyh: val }).then((res) => {
          const resFilter = {}
          if (res.code === 200 && res.data) {
            console.log('获取转诊自动填充信息', res)
            const result = res.data
            Object.keys(result).forEach(key => {
              if (result[key] && (JSON.stringify(result[key]) !== '{}') && Object.keys(that.defaultData).includes(key)) {
                resFilter[key] = String(result[key])
              }
            })
          }
          that.form.setFieldsValue(Object.assign(that.defaultData, resFilter, { zyh: val }))
          that.$nextTick(() => {
            that.viewInit()
          })
        }).catch(() => {
          console.log('申请转诊自动填充查询服务错误！')
          that.form.setFieldsValue(Object.assign(that.defaultData, { zyh: val }))
        })
      } else {
        that.form.setFieldsValue(Object.assign(that.defaultData, { zyh: val }))
      }
    },
    outDoctorSearch (val) {
      console.log(val, this.$refs)
    },
    inDoctorSearch (val) {
    },
    outDoctorChange (val, options) {
      this.form.setFieldsValue({ outDoctorName: options.componentOptions.children[0].text })
    },
    inDoctorChange (val, options) {
      this.form.setFieldsValue({ inDoctorName: options.componentOptions.children[0].text })
    },
    inHospitalChange (val, options) {
      var that = this
      this.form.setFieldsValue({ inHospitalName: options.componentOptions.children[0].text })
      function clear () {
        that.form.setFieldsValue({ inDeptCode: undefined, inDeptName: '', inDoctorCode: undefined, inDoctorName: '' })
        that.rollinInfoForm.inDeptCode.selectList = []
        that.rollinInfoForm.inDoctorCode.selectList = []
      }
      getHospDeptInfo(val).then((res) => {
        if (res && res[0] && res[0].value) {
          that.form.setFieldsValue({ inDeptCode: res[0].value })
          that.rollinInfoForm.inDeptCode.selectList = res
          this.inDeptChange(res[0].value)
        } else {
          clear()
        }
      }).catch((err) => {
        clear()
        that.$message.error('转出科室字典服务出错,请稍后重试！')
        console.log(err)
      })
    },
    inDeptChange (val) {
      var that = this
      const label = that.rollinInfoForm.inDeptCode.selectList.find(item => { return item.value === val }).label
      this.form.setFieldsValue({ inDeptName: label })
      const formdata = that.form.getFieldsValue()
      const params = {
        hopitalInfoId: formdata.inHospitalCode,
        deptId: val
      }
      getDoctorInfoList(params).then((res) => {
        if (res) {
          that.rollinInfoForm.inDoctorCode.selectList = res
        } else {
          that.rollinInfoForm.inDoctorCode.selectList = []
        }
      }).catch((err) => {
        that.$message.error('医生字典服务出错,请稍后重试！')
        console.log(err)
      })
      that.form.setFieldsValue({ inDoctorCode: undefined, inDoctorName: '' })
    },
    outHospitalChange (val, options) {
      var that = this
      that.form.setFieldsValue({ outHospitalName: options.componentOptions.children[0].text })
      function clear () {
        that.form.setFieldsValue({ outDeptCode: undefined, outDeptName: '', outDoctorCode: undefined, outDoctorName: '' })
        that.outInfoForm.outDeptCode.selectList = []
        that.outInfoForm.outDoctorCode.selectList = []
      }
      getHospDeptInfo(val).then((res) => {
        if (res && res[0] && res[0].value) {
          that.form.setFieldsValue({ outDeptCode: res[0].value })
          that.outInfoForm.outDeptCode.selectList = res
          this.outDeptChange(res[0].value)
        } else {
          clear()
        }
      }).catch((err) => {
        clear()
        that.$message.error('转出科室字典服务出错,请稍后重试！')
        console.log(err)
      })
    },
    outDeptChange (val) {
      var that = this
      const label = that.outInfoForm.outDeptCode.selectList.find(item => { return item.value === val }).label
      that.form.setFieldsValue({ outDeptName: label })
      const formdata = that.form.getFieldsValue()
      const params = {
        hopitalInfoId: formdata.outHospitalCode,
        deptId: val
      }
      getDoctorInfoList(params).then((res) => {
        if (res) {
          that.outInfoForm.outDoctorCode.selectList = res
        } else {
          that.outInfoForm.outDoctorCode.selectList = []
        }
      }).catch((err) => {
        that.$message.error('医生字典服务出错,请稍后重试！')
      })
      that.form.setFieldsValue({ outDoctorCode: undefined, outDoctorName: '' })
    },
    onDisabled (formlist) {
      if (this.disabledList && this.status !== 'details') {
        Object.keys(formlist).forEach((key) => {
          if (this.disabledList.includes(formlist[key].key)) {
            formlist[key].disabled = true
          }
        })
      }
      if (this.status === 'details') {
        Object.keys(formlist).forEach((key) => {
          formlist[key].disabled = true
        })
      }
    },
    viewInit () {
      if (this.defaultData.outDeptCode) {
        getHospDeptInfo(this.defaultData.outHospitalCode).then((res) => {
          this.outInfoForm.outDeptCode.selectList = res
        })
        const params = {
          hopitalInfoId: this.defaultData.outHospitalCode,
          deptId: this.defaultData.outDeptCode
        }
        getDoctorInfoList(params).then((res) => {
          this.outInfoForm.outDoctorCode.selectList = res
        })
      }
      if (this.defaultData.inDeptCode) {
        getHospDeptInfo(this.defaultData.inHospitalCode).then((res) => {
          this.rollinInfoForm.inDeptCode.selectList = res
        })
        const params = {
          hopitalInfoId: this.defaultData.inHospitalCode,
          deptId: this.defaultData.inDeptCode
        }
        getDoctorInfoList(params).then((res) => {
          this.rollinInfoForm.inDoctorCode.selectList = res
        })
      }
    },
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$notification['error']({
            message: 'Received values of form:',
            description: values
          })
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
